#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
环境检查脚本
检查运行人脸识别系统所需的依赖是否正确安装
"""

import sys
import os
import importlib.util

def check_python_version():
    """检查Python版本"""
    print(f"Python版本: {sys.version}")
    
    if sys.version_info < (3, 7):
        print("❌ Python版本过低，需要Python 3.7或更高版本")
        return False
    elif sys.version_info >= (3, 12):
        print("⚠️  Python版本较新，某些依赖包可能不兼容")
        return True
    else:
        print("✅ Python版本符合要求")
        return True

def check_package(package_name, import_name=None):
    """检查包是否安装"""
    if import_name is None:
        import_name = package_name
    
    try:
        spec = importlib.util.find_spec(import_name)
        if spec is None:
            print(f"❌ {package_name} 未安装")
            return False
        else:
            # 尝试导入以确保包可以正常使用
            module = importlib.import_module(import_name)
            if hasattr(module, '__version__'):
                version = module.__version__
                print(f"✅ {package_name} 已安装 (版本: {version})")
            else:
                print(f"✅ {package_name} 已安装")
            return True
    except Exception as e:
        print(f"❌ {package_name} 导入失败: {str(e)}")
        return False

def check_opencv():
    """特别检查OpenCV"""
    try:
        import cv2
        print(f"✅ OpenCV 已安装 (版本: {cv2.__version__})")
        
        # 检查人脸识别模块
        try:
            recognizer = cv2.face.LBPHFaceRecognizer_create()
            print("✅ OpenCV人脸识别模块可用")
            return True
        except Exception as e:
            print(f"❌ OpenCV人脸识别模块不可用: {str(e)}")
            print("   请安装opencv-contrib-python而不是opencv-python")
            return False
    except ImportError:
        print("❌ OpenCV 未安装")
        return False

def check_camera():
    """检查摄像头"""
    try:
        import cv2
        cap = cv2.VideoCapture(0)
        if cap.isOpened():
            ret, frame = cap.read()
            cap.release()
            if ret:
                print("✅ 摄像头可用")
                return True
            else:
                print("⚠️  摄像头已连接但无法读取画面")
                return False
        else:
            print("❌ 无法打开摄像头")
            return False
    except Exception as e:
        print(f"❌ 摄像头检查失败: {str(e)}")
        return False

def check_file_structure():
    """检查文件结构"""
    required_files = [
        'main.py',
        'tkgui.py', 
        'face_recognition.py',
        'database.py',
        'requirements.txt'
    ]
    
    required_dirs = [
        'data',
        'resources'
    ]
    
    missing_files = []
    missing_dirs = []
    
    for file in required_files:
        if not os.path.exists(file):
            missing_files.append(file)
    
    for dir in required_dirs:
        if not os.path.exists(dir):
            missing_dirs.append(dir)
    
    if missing_files:
        print(f"❌ 缺少文件: {', '.join(missing_files)}")
    else:
        print("✅ 所有必需文件都存在")
    
    if missing_dirs:
        print(f"⚠️  缺少目录: {', '.join(missing_dirs)} (程序会自动创建)")
    else:
        print("✅ 所有必需目录都存在")
    
    return len(missing_files) == 0

def main():
    """主检查函数"""
    print("=" * 50)
    print("人脸识别系统环境检查")
    print("=" * 50)
    
    checks = []
    
    print("\n1. 检查Python版本...")
    checks.append(check_python_version())
    
    print("\n2. 检查必需的包...")
    packages = [
        ('numpy', 'numpy'),
        ('Pillow', 'PIL'),
        ('ttkthemes', 'ttkthemes'),
        ('tkinter', 'tkinter')
    ]
    
    for package_name, import_name in packages:
        checks.append(check_package(package_name, import_name))
    
    print("\n3. 检查OpenCV...")
    checks.append(check_opencv())
    
    print("\n4. 检查摄像头...")
    checks.append(check_camera())
    
    print("\n5. 检查文件结构...")
    checks.append(check_file_structure())
    
    print("\n" + "=" * 50)
    if all(checks):
        print("✅ 所有检查通过！系统可以正常运行。")
        print("您可以运行 'python main.py' 或双击 '启动人脸识别系统.bat' 来启动程序。")
        return 0
    else:
        print("❌ 发现问题，请根据上述提示解决后再试。")
        print("\n建议的解决步骤：")
        print("1. 安装或更新依赖包：pip install -r requirements.txt")
        print("2. 如果使用opencv-python，请卸载后安装opencv-contrib-python：")
        print("   pip uninstall opencv-python")
        print("   pip install opencv-contrib-python")
        print("3. 检查摄像头连接和权限")
        return 1

if __name__ == "__main__":
    try:
        exit_code = main()
        input("\n按Enter键退出...")
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n\n检查被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n检查过程中发生错误: {str(e)}")
        input("\n按Enter键退出...")
        sys.exit(1)
